import XLSX from 'xlsx';
import { importGoods } from './api';
import { message } from '@/utils/util';

export default {
  name: 'import-goods-price-modal',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    topChannelList: {
      type: Array,
      default: () => [],
    },
  },

  data() {
    return {
      formValue: {},
      formRules: {
        topChannelCode: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (!this.formValue.topChannelCode) {
                callback('顶级渠道不能为空');
              } else {
                callback();
              }
            },
          },
        ],
        taskList: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (!this.formValue.taskDetails) {
                callback('导入信息不能为空');
              } else {
                callback();
              }
            },
          },
        ],
      },
      formLabelWidth: '100px',
      importing: false,
    };
  },
  watch: {},
  methods: {
    async onSubmit(name) {
      this.$refs[name].validate(async valid => {
        if (valid) {
          this.importing = true;
          const taskDetails = this.formValue.taskDetails;
          const taskDetailsArray = [];
          taskDetails.forEach(item => {
            taskDetailsArray.push({
              ...item,
              activityData: {
                channelCode: item.channelCode,
                goodsCode: item.goodsCode,
                newChannelPrice: item.newChannelPrice,
                newActivityPrice: item.newActivityPrice,
                limitFrequency: item.limitFrequency,
                limitNum: item.limitNum,
                activityPriceLimit: item.activityPriceLimit,
              },
            });
          });
          try {
            await importGoods(this.formValue.topChannelCode, taskDetailsArray);
            message('提示', '导入成功', 'success');
            this.onClose();
          } catch (e) {
            message('错误', '导入失败:' + e.message, 'error');
          }
          this.importing = false;
        }
      });
    },
    onClose() {
      this.formValue = {};
      this.$refs.formRef.resetFields();
      this.$refs.upload.uploadFiles = [];
      this.$emit('close');
    },
    onChange(file) {
      const reader = new FileReader();
      reader.onload = e => {
        console.log(e);
        let data = e.target.result;
        const workbook = XLSX.read(data, { type: 'buffer' });
        const [sheetName] = workbook.SheetNames;
        const sheetInfo = workbook.Sheets[sheetName];
        console.log(sheetInfo);
        const parsedSheetInfo = XLSX.utils.sheet_to_json(sheetInfo, { raw: false });
        console.log('parsedSheetInfo', parsedSheetInfo);
        const result = parsedSheetInfo.map((item, index) => {
          return {
            rowNo: index + 2,
            costPrice: String(item['成本价'] || ''),
            retailPrice: String(item['零售价'] || ''),
            minPrice: String(item['起送价'] || ''),
            channelPrice: String(item['商品原价'] || ''),
            activityPrice: String(item['商品特价'] || ''),
            salesRank: String(item['销售排名'] || ''),
            monthSales: String(item['月售'] || ''),
            competeChannelPrice: String(item['竞对原价最低价'] || ''),
            competeActivityPrice: String(item['竞对特价最低价'] || ''),
            newChannelPrice: String(item['调原价'] || ''),
            newActivityPrice: String(item['调特价'] || ''),
            competeMaxSales: String(item['竞对最高销量'] || ''),
            cellularSales: String(item['蜂窝总销量'] || ''),
            limitFrequency: String(item['限购频率'] || ''),
            limitNum: String(item['限购数量'] || ''),
            activityPriceLimit: String(item['特价限购'] || ''),
            goodsCode: String(item['商品编码'] || ''),
            channelCode: String(item['渠道编码'] || ''),
            cellularCode: String(item['所属蜂窝'] || ''),
          };
        });
        console.log('从excel中读取的result', result);
        if (result && result.length > 0) {
          const list = [];
          const isNotNext = result.some((item, index) => {
            const rowText = `第${index + 2}行`;
            const obj = {};
            if (!item.channelCode) {
              message('提示', rowText + '渠道编码为空', 'error');
              return true;
            } else {
              item.channelCode = item.channelCode.trim();
            }
            obj.channelCode = item.channelCode;
            if (!item.goodsCode) {
              message('提示', rowText + '商品编码为空', 'error');
              return true;
            } else {
              item.goodsCode = item.goodsCode.trim();
            }
            if (item.cellularCode) {
              obj.cellularCode = item.cellularCode;
            }
            obj.goodsCode = item.goodsCode;
            const newChannelPrice = item.newChannelPrice;
            const limitFrequency = item.limitFrequency; // 限购频率
            const limitNum = item.limitNum; //限购数量
            const newActivityPrice = item.newActivityPrice;
            const activityPriceLimit = item.activityPriceLimit;
            if (!(newChannelPrice || limitFrequency || limitNum || newActivityPrice || activityPriceLimit)) {
              message('提示', rowText + '没有设置调价需求', 'error');
              return true;
            }
            if (newChannelPrice) {
              if (number <= 0) {
                message('提示', rowText + '调原价小于等于0', 'error');
                return true;
              }
              const number = this.isNumber(newChannelPrice);
              if (!number) {
                message('提示', rowText + '调原价不是数字', 'error');
                return true;
              }
              obj.newChannelPrice = this.mathFloor(number);
            }
            if (limitFrequency) {
              const number = this.isNumber(limitFrequency);
              if (number === 0) {
                message('提示', rowText + '限购频率不能为0', 'error');
                return true;
              }
              if (!number) {
                message('提示', rowText + '限购频率不是数字', 'error');
                return true;
              }
              if (number > 9999 || (number < 1 && number !== -1)) {
                message('提示', rowText + '限购频率不能小于等于1大于9999', 'error');
                return true;
              }
              obj.limitFrequency = this.mathFloor(number);
            }
            if (limitNum) {
              const number = this.isNumber(limitNum);
              if (number === 0) {
                message('提示', rowText + '限购数量不能为0', 'error');
                return true;
              }
              if (number < -1) {
                message('提示', rowText + '限购数量必须大于等于-1', 'error');
                return true;
              }
              if (!number) {
                message('提示', rowText + '限购数量不是数字', 'error');
                return true;
              }
              obj.limitNum = this.mathFloor(number);
            }
            if (newActivityPrice) {
              const number = this.isNumber(newActivityPrice);
              if (number <= 0) {
                message('提示', rowText + '调特价小于等于0', 'error');
                return true;
              }
              if (!number) {
                message('提示', rowText + '调特价不是数字', 'error');
                return true;
              }
              obj.newActivityPrice = this.mathFloor(number);
            }
            if (activityPriceLimit) {
              const number = this.isNumber(activityPriceLimit);

              if (number === 0) {
                message('提示', rowText + '特价限购不能为0', 'error');
                return true;
              }
              if (number < -1) {
                message('提示', rowText + '特价限购必须大于等于-1', 'error');
                return true;
              }
              if (!number) {
                message('提示', rowText + '特价限购不是数字', 'error');
                return true;
              }
              obj.activityPriceLimit = this.mathFloor(number);
            }
            const costPrice = item.costPrice;
            console.log('costPrice', costPrice);
            if (costPrice) {
              const number = this.isNumber(costPrice);
              if (!number) {
                message('提示', rowText + '成本价不是数字', 'error');
                return true;
              }
              obj.costPrice = this.mathFloor(number);
            }
            const channelPrice = item.channelPrice;
            if (channelPrice) {
              const number = this.isNumber(channelPrice);
              if (!number) {
                message('提示', rowText + '商品原价不是数字', 'error');
                return true;
              }
              obj.channelPrice = this.mathFloor(number);
            }
            obj.minPrice = item.minPrice;
            const competeChannelPrice = item.competeChannelPrice;
            if (competeChannelPrice) {
              const number = this.isNumber(competeChannelPrice);
              if (!number) {
                message('提示', rowText + '竞对原价最低价不是数字', 'error');
                return true;
              }
              obj.competeChannelPrice = this.mathFloor(number);
            }
            const competeActivityPrice = item.competeActivityPrice;
            if (competeActivityPrice) {
              const number = this.isNumber(competeActivityPrice);
              if (!number) {
                message('提示', rowText + '竞对特价最低价不是数字', 'error');
                return true;
              }
              obj.competeActivityPrice = this.mathFloor(number);
            }
            const competeMaxSales = item.competeMaxSales;
            if (competeMaxSales) {
              const number = this.isNumber(competeMaxSales);
              if (!number) {
                message('提示', rowText + '竞对最高销量不是数字', 'error');
                return true;
              }
              obj.competeMaxSales = this.mathFloor(number);
            }
            const cellularSales = item.cellularSales;
            if (cellularSales) {
              const number = this.isNumber(cellularSales);
              if (!number) {
                message('提示', rowText + '蜂窝总销量不是数字', 'error');
                return true;
              }
              obj.cellularSales = this.mathFloor(number);
            }
            const retailPrice = item.retailPrice;
            if (retailPrice) {
              const number = this.isNumber(retailPrice);
              if (!number) {
                message('提示', rowText + '商品原价不是数字', 'error');
                return true;
              }
              obj.retailPrice = this.mathFloor(number);
            }
            const activityPrice = item.activityPrice;
            if (activityPrice) {
              const number = this.isNumber(activityPrice);
              if (!number) {
                message('提示', rowText + '商品特价不是数字', 'error');
                return true;
              }
              obj.activityPrice = this.mathFloor(number);
            }
            const salesRank = item.salesRank;
            if (salesRank) {
              const number = this.isNumber(salesRank);
              if (!number) {
                message('提示', rowText + '销售排名不是数字', 'error');
                return true;
              }
              obj.salesRank = this.mathFloor(number);
            }

            const monthSales = item.monthSales;
            if (monthSales) {
              const number = this.isNumber(monthSales);
              if (!number) {
                message('提示', rowText + '月售不是数字', 'error');
                return true;
              }
              obj.monthSales = this.mathFloor(number);
            }
            list.push(obj);
            return false;
          });
          if (isNotNext) {
            return;
          }
          console.log('importList', list);
          this.formValue.taskDetails = list;
          this.$refs.formRef.validateField('taskList');
        }
        message('提示', '文件上传成功', 'success');
      };
      reader.readAsArrayBuffer(file.raw);
    },
    mathFloor(number) {
      if (!number) {
        return 0;
      }
      return Math.floor(number * 100) / 100;
    },
    isNumber(string) {
      if (!string) {
        return null;
      }
      const number = Number(string);
      if (number === 0) {
        return number;
      }
      if (number) {
        return number;
      }
      return null;
    },
    onError(err) {
      console.log('err:', err);
    },
  },
  mounted() {},
};
